package com.hunttown.mes.common.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title: 读取本地xml文件
 * @author: wangjunfu
 * @date: 2020年10月11日 11:45
 * @description:
 */
public class ReadXmlUtils {

    /**
     * 只获取一级xml节点内容，单组以Map形式返回
     * 多组，则以List<Map>的方式返回
     *
     * @param path     绝对路径
     * @param nodename 节点名称
     * @return map
     */
    public static List<Map<String, String>> getXmlContent(String path, String nodename) {

        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map;

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(path);

            NodeList nodelist = document.getElementsByTagName(nodename);

            for (int i = 0; i < nodelist.getLength(); i++) {
                map = new HashMap<>();
                Element ele = (Element) nodelist.item(i);
                NodeList childNodes = ele.getChildNodes();

                for (int j = 0; j < childNodes.getLength(); j++) {
                    Node n = childNodes.item(j);
                    if (!n.getNodeName().equals("#text")) {
                        map.put(n.getNodeName(), n.getTextContent());
                    }
                }

                list.add(map);
            }

        } catch (ParserConfigurationException | IOException | SAXException e) {
            e.printStackTrace();
        }

        return list;
    }
}
